package stocks

import (
	"fmt"
	"strings"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/finego/backends/utils"
	"gitee.com/chenrh/gotoolkit/conv"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	// "strings"
)

// StrockGroupController serves the "/", "/ping" and "/hello".
type StrockGroupController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context

	// Our UserService, it's an interface which
	// is binded from the main application.
	//Service services.UserService
}

// BeforeActivation 注册自定义的路由
func (c *StrockGroupController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/center/group", "GroupManager")
	b.Handle("POST", "/group/save", "SaveGroup")
	b.Handle("POST", "/group/delete", "DeleteGroup")
	b.Handle("POST", "/group/save_distribution", "SaveDistribution")
	b.Handle("GET", "/group/get_grpid_by_code", "GetGrpID")
}

// GroupManager  股票权衡界面
func (c *StrockGroupController) GroupManager() mvc.Result {

	_, user := utils.UserCache(c.Ctx)

	datasql := fmt.Sprintf("select a.grp_id, a.grp_name, a.order_num from stk_group a where a.user_id = '%d' order by a.order_num asc", user.UserID)
	arr, _ := app.DB.Select(datasql)

	return mvc.View{
		Name: "stocks/stocks.group.html",
		Data: iris.Map{
			"Title":     "股票分组维护",
			"GroupList": arr,
		},
	}
}

// SaveGroup 保存评论
func (c *StrockGroupController) SaveGroup() {

	grpid := c.Ctx.FormValue("grp_id")
	grpname := c.Ctx.FormValue("grp_name")
	grporder := c.Ctx.FormValue("grp_order")
	action := c.Ctx.FormValue("action")

	haslogin, user := utils.UserCache(c.Ctx)

	if !haslogin {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请选登录"})
		return
	}

	if len(grpname) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "组名称不能为空"})
		return
	}

	if action == "create" {
		md := models.STK_GROUP{
			USER_ID:   user.UserID,
			GRP_NAME:  grpname,
			ORDER_NUM: conv.ToFloat64(grporder, 10),
		}
		md.CreatedBy = user.NickName
		app.GetDB().Create(&md)
	} else if action == "edit" {
		md := models.STK_GROUP{}
		db := app.GetDB()
		db.First(&md, grpid)
		md.GRP_NAME = grpname
		md.ORDER_NUM = conv.ToFloat64(grporder, 10)
		md.UpdatedBy = user.NickName
		db.Save(&md)
	}

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}

// DeleteGroup 删除分组
func (c *StrockGroupController) DeleteGroup() {

	id := c.Ctx.FormValue("grp_id")
	groupID := conv.ToInt64(id, -1)

	mod := models.STK_GROUP{
		GRP_ID: groupID,
	}

	app.GetDB().Delete(&mod)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}

// SaveDistribution 保存股票分组结果
func (c *StrockGroupController) SaveDistribution() {

	grpIDs := c.Ctx.FormValue("grp_ids")
	code := c.Ctx.FormValue("code")

	if len(grpIDs) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "至少选择一项分组"})
		return
	}
	_, user := utils.UserCache(c.Ctx)

	arr := strings.Split(grpIDs, ",")

	db := app.GetDB()

	db.Exec("DELETE FROM stk_group_member WHERE user_id = ? AND company_code = ?", user.UserID, code)

	list := []models.STK_GROUP_MEMBER{}
	for _, grpid := range arr {
		groupID := conv.ToInt64(grpid, -1)
		if groupID == -1 {
			continue
		}

		mod := models.STK_GROUP_MEMBER{
			GRP_ID:       groupID,
			USER_ID:      user.UserID,
			COMPANY_CODE: code,
			ORDER_NUM:    10,
		}
		list = append(list, mod)
	}

	db.Create(&list)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}

// GetGrpID 保存股票分组结果
func (c *StrockGroupController) GetGrpID() {
	code := c.Ctx.FormValue("code")
	if len(code) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "股票代码不能为空"})
		return
	}
	_, user := utils.UserCache(c.Ctx)

	datasql := `SELECT a.grp_id FROM stk_group_member a WHERE a.company_code = ? and a.user_id = ?`
	arr, _ := app.DB.Select(datasql, code, user.UserID)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK", "data": arr})
	return
}
